package com.aidex.system.service.impl;

import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.StringUtils;
import com.aidex.risk.domain.*;
import com.aidex.system.domain.CargoDetail;
import com.aidex.system.domain.Waybill;
import com.aidex.system.domain.WaybillDetail;
import com.aidex.system.mapper.WaybillMapper;
import com.aidex.system.service.CargoDetailService;
import com.aidex.system.service.NlpService;
import com.aidex.system.service.WaybillDetailService;
import com.aidex.system.service.WaybillService;
import com.github.pagehelper.PageInfo;
import org.apache.lucene.search.spell.NGramDistance;
import org.apache.lucene.search.spell.StringDistance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 运单管理Service业务层处理
 * @author jmy
 * @email jmyinjg@163.com
 * @date 2021-10-04
 */
@Service
@Transactional(readOnly = false)
public class WaybillServiceImpl extends BaseServiceImpl<WaybillMapper, Waybill> implements WaybillService
{
    private static final Logger log = LoggerFactory.getLogger(WaybillServiceImpl.class);

    @Autowired
    private NlpService nlpService;
    @Autowired
    private CargoDetailService cargoDetailService;
    @Autowired
    private WaybillDetailService waybillDetailService;

    /**
     * 获取单条数据
     * @param waybill 运单管理
     * @return 运单管理
     */
    @Override
    public Waybill get(Waybill waybill)
    {
        Waybill dto = super.get(waybill);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 运单管理id
     * @return 运单管理
     */
    @Override
    public Waybill get(String id)
    {
        Waybill dto = super.get(id);
        return dto;
    }


    /**
     * 查询运单管理列表
     * @param waybill 运单管理
     * @return 运单管理
     */
    @Override
    public List<Waybill> findList(Waybill waybill)
    {
        return super.findList(waybill);
    }

    /**
     * 分页查询运单管理列表
     * @param waybill 运单管理
     * @return 运单管理
     */
    @Override
    public PageInfo<Waybill> findPage(Waybill waybill)
    {
        return super.findPage(waybill);
    }

    /**
     * 保存运单管理
     * @param waybill
     * @return 结果
     */
    @Override
    public boolean save(Waybill waybill)
    {
        waybill.setStatus(0);
        return super.save(waybill);
    }


    /**
     * 删除运单管理信息
     * @param waybill
     * @return 结果
     */
    @Override
    public boolean remove(Waybill waybill)
    {
        return super.remove(waybill);
    }

    /**
     * 批量删除运单管理
     * @param ids 需要删除的运单管理ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteWaybillByIds(String[] ids)
    {
        return mapper.deleteWaybillByIds(ids);
    }

    @Override
    public Waybill get(String waybillNo, String dataSource) {
        return mapper.getByBillno(waybillNo,dataSource);
    }

    @Override
    public Waybill getUnSend(String waybillNo) {
        return mapper.getUnSend(waybillNo);
    }

    @Override
    public void deleteWaybillByBillno(String waybillNo, String dataSource) {
        mapper.deleteWaybillByBillno(waybillNo);
    }

    //差异备案记录
    @Override
    public resultResponseT<wlpt_diff_producet_queryResponse> queryDiffProducetCommonLevel(Waybill waybill) {
        if(waybill.getDiffProductSn().equals(null)){
            return null;
        }
        resultResponseT<wlpt_diff_producet_queryResponse> response = new resultResponseT<>();
        wlpt_diff_producet_query request = new wlpt_diff_producet_query();
        String[] sns= waybill.getDiffProductSn().split(",");
        request.setDifferentiationProductCode(waybill.getDiffProductSn().split(","));
        /*String json = JsonHelper.getInstance().writeValueAsString(request);
        String res = HttpUtils.sendPost1("http://10.80.32.101:7080/ESBService/HRDEVAD",json);
        return JsonHelper.getInstance().readValue(res,wlpt_diff_producet_queryResponse.class);*/
        List<wlpt_diff_producet_queryResponse> responses = new ArrayList<>();
        for(int i=0;i<sns.length;i++){
            wlpt_diff_producet_queryResponse res = new wlpt_diff_producet_queryResponse();
            res.setCompare(true);//是否查到特货代码
            res.setDifferentiationProductCode(sns[i]);//特货代码
            responses.add(res);
        }
        response.setData(responses);
        return response;
    }

    @Override
    public  resultResponseT<wlpt_agent_scoreResponse> queryTradeAgentLevel(Waybill waybill) {
        resultResponseT<wlpt_agent_scoreResponse> result = new resultResponseT<>();
        wlpt_agent_score request = new wlpt_agent_score();
        request.setAgentCode(waybill.getAgentCode());
        request.setAgentName(waybill.getOrganization());
        request.setSourceCode(waybill.getDataSource()=="CFPS"?1:4);
        /*String json =JsonHelper.getInstance().writeValueAsString(request);
        String res =HttpUtils.sendPost1("http://10.80.32.101:7080/ESBService/HRDEVAD",json);
        return JsonHelper.getInstance().readValue(res,wlpt_agent_scoreResponse.class);*/
        wlpt_agent_scoreResponse response = new wlpt_agent_scoreResponse();
        response.setLevel("C");//等级
        response.setDomesticRank(1);
        response.setOrgName("测试物流公司");
        response.setType(1);
        response.setYear("2021");
        response.setUpdateTime("1627965271000");
        response.setQuarter("1");
        List<wlpt_agent_scoreResponse> responses = new ArrayList<>();
        responses.add(response);
        result.setData(responses);
        return result;
    }
    @Override
    public syncEmergency<syncEmergencyAirport> queryEmergencyAirport(Waybill waybill)   {
        syncEmergency<syncEmergencyAirport> result = new syncEmergency<syncEmergencyAirport>();
        result.setFrom("CFPS");
        result.setMethod("syncEmergencyFlight");
        result.setTransNo("10476603");
        List<syncEmergencyAirport> list=new ArrayList<>();
        syncEmergencyAirport airport = new syncEmergencyAirport();
        airport.setAirPortCode(waybill.getFlightNo());
        airport.setAirPortName(waybill.getFlightNo());
        airport.setStartupDisable("1");//是否重点航班，航线
        list.add(airport);
        result.setData(list);
        return result;
    }

/*
    public syncEmergency<syncEmergencyAirport> syncEmergencyAirport()   {
        resultResponse result = new resultResponse();
        result.setStatus("200");
        result.setMessage("success");
        result.setTimestamp(1622105424285L);
        return result;
    }


    public syncEmergency<syncEmergencyFlight> syncEmergencyFlight()   {
        resultResponse result = new resultResponse();
        result.setStatus("200");
        result.setMessage("success");
        result.setTimestamp(1622105424285L);
        return result;
    }

    public syncEmergency<syncEmergencyGuard> syncEmergencyGuard()   {
        resultResponse result = new resultResponse();
        result.setStatus("200");
        result.setMessage("success");
        result.setTimestamp(1622105424285L);
        return result;
    }*/

    @Override
    @Transactional(readOnly = false)
    public void handleBatchWaybill() {
        // 获取未处理运单数据，一次处理一百条
        List<Waybill> list = mapper.getUnHandleBillList(100);
        for (Waybill waybill : list) {
            waybill.setStatus(1);
            /**
             * 1、校验数据
             * 2、查询航班是否属于重点航班或者航线
             * 3、查询代理人信用等级
             * 4、分词
             */
            if (StringUtils.isBlank(waybill.getFlightNo()) || StringUtils.isBlank(waybill.getAgentCode())
                    || StringUtils.isBlank(waybill.getGoodsName())) {
                mapper.update(waybill);
                continue;
            }
            // 判断是否是重点航班
            syncEmergency<syncEmergencyAirport> isImportant = this.queryEmergencyAirport(waybill);
            syncEmergencyAirport airport = isImportant.getData().get(0);
            waybill.setIsImportantFlights("N");
            if ("1".equals(airport.getStartupDisable())) {
                waybill.setIsImportantFlights("Y");
            }
            // 查询代理人信用等级
            resultResponseT<wlpt_agent_scoreResponse> infos = this.queryTradeAgentLevel(waybill);
            wlpt_agent_scoreResponse agentInfo = infos.getData().get(0);
            waybill.setAgentLevel(agentInfo.getLevel());
            // 进行分词
            List<String> words = nlpService.getCutList(waybill.getGoodsName());
            if (words.isEmpty()) {
                mapper.update(waybill);
                continue;
            }
            List<WaybillDetail> details = new ArrayList<>();
            // 生成明细记录
            for (String word : words) {
                WaybillDetail detail = new WaybillDetail();
                detail.setTradeName(word);
                detail.setTradeNameKey(word);
                detail.setWaybillId(waybill.getId());
                // 计算货物风险等级
                // 判断是否重点航班或者航线
                if ("Y".equals(waybill.getIsImportantFlights())) {
                    detail.setTradeRiskClassification("高风险");
                } else {
                    // 判断清单中有没有数据，有的话返回高风险
                    CargoDetail cargoDetail = cargoDetailService.getByName(word);
                    if (cargoDetail == null) {
                        detail.setTradeType("0");
                        // 判断差异化备案记录，在备案中返回低风险，否则返回普通风险
//                        this.queryDiffProducetCommonLevel();
                        if (true) {
                            detail.setTradeRiskClassification("低风险");
                        } else {
                            detail.setTradeRiskClassification("普通风险");
                        }
                    } else {
                        detail.setTradeType(cargoDetail.getType().toString());
                        detail.setTradeRiskClassification("高风险");
                    }
                }
                // 计算综合货物风险
                switch (detail.getTradeRiskClassification()) {
                    case "高风险":
                        detail.setTradeRiskRating("高风险");
                        break;
                    case "普通":
                        switch (waybill.getAgentLevel()) {
                            case "A":
                                detail.setTradeRiskRating("优先");
                                break;
                            case "B":
                                detail.setTradeRiskRating("普通");
                                break;
                            default:
                                detail.setTradeRiskRating("严控");
                        }
                        break;
                    default:
                        switch (waybill.getAgentLevel()) {
                            case "A":
                                detail.setTradeRiskRating("低风险");
                                break;
                            case "B":
                                detail.setTradeRiskRating("普通");
                                break;
                            default:
                                detail.setTradeRiskRating("严控");
                        }
                }
                waybillDetailService.save(detail);
                details.add(detail);
            }
            // 计算运单的货物风险等级和综合风险等级
            if (details.stream().filter(row -> "高风险".equals(row.getTradeRiskClassification())).count() > 0) {
                waybill.setRiskClassification("高风险");
            } else if (details.stream().filter(row -> "低风险".equals(row.getTradeRiskClassification())).count() > 0) {
                waybill.setRiskClassification("低风险");
            } else {
                waybill.setRiskClassification("普通");
            }
            if (details.stream().filter(row -> "高风险".equals(row.getTradeRiskRating())).count() > 0) {
                waybill.setRiskRating("高风险");
            } else if (details.stream().filter(row -> "严控".equals(row.getTradeRiskRating())).count() > 0) {
                waybill.setRiskRating("严控");
            } else if (details.stream().filter(row -> "普通".equals(row.getTradeRiskRating())).count() > 0) {
                waybill.setRiskRating("普通");
            } else if (details.stream().filter(row -> "优先".equals(row.getTradeRiskRating())).count() > 0) {
                waybill.setRiskRating("优先");
            } else {
                waybill.setRiskRating("低风险");
            }
            mapper.update(waybill);
        }
    }

    public static void main(String[] args) {
        StringDistance distance = new NGramDistance();
        System.out.println(distance.getDistance("中国", "中国的"));
    }

}